<template>
  <div class="notification-center">
    <!-- 通知铃铛图标 -->
    <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="notification-badge">
      <el-button 
        type="text" 
        @click="toggleNotificationPanel"
        class="notification-button"
      >
        <el-icon :size="20">
          <Bell />
        </el-icon>
      </el-button>
    </el-badge>

    <!-- 通知面板 -->
    <el-drawer
      v-model="showNotificationPanel"
      title="通知中心"
      direction="rtl"
      size="400px"
      :before-close="handleClose"
    >
      <div class="notification-content">
        <!-- 操作按钮 -->
        <div class="notification-actions">
          <el-button size="small" @click="markAllAsRead" :disabled="unreadCount === 0">
            全部已读
          </el-button>
          <el-button size="small" @click="clearAll" type="danger" plain>
            清空通知
          </el-button>
        </div>

        <!-- 通知列表 -->
        <div class="notification-list">
          <div 
            v-for="notification in notifications" 
            :key="notification.id"
            class="notification-item"
            :class="{ 'unread': !notification.read }"
            @click="markAsRead(notification)"
          >
            <div class="notification-header">
              <span class="notification-title">{{ notification.title }}</span>
              <span class="notification-time">{{ formatTime(notification.timestamp) }}</span>
            </div>
            <div class="notification-content-text">
              {{ notification.content }}
            </div>
            <div class="notification-sender" v-if="notification.senderName">
              来自：{{ notification.senderName }}
            </div>
          </div>
          
          <div v-if="notifications.length === 0" class="empty-notifications">
            <el-empty description="暂无通知" />
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { Bell } from '@element-plus/icons-vue'
import webSocketManager from '../utils/websocket'

// 响应式数据
const showNotificationPanel = ref(false)
const notifications = ref([])

// 计算属性
const unreadCount = computed(() => {
  return notifications.value.filter(n => !n.read).length
})

// 方法
const toggleNotificationPanel = () => {
  showNotificationPanel.value = !showNotificationPanel.value
}

const handleClose = () => {
  showNotificationPanel.value = false
}

const markAsRead = (notification) => {
  notification.read = true
  saveNotificationsToStorage()
}

const markAllAsRead = () => {
  notifications.value.forEach(n => n.read = true)
  saveNotificationsToStorage()
}

const clearAll = () => {
  notifications.value = []
  saveNotificationsToStorage()
}

const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 1天内
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return date.toLocaleDateString()
  }
}

const addNotification = (notification) => {
  const newNotification = {
    id: Date.now() + Math.random(),
    ...notification,
    read: false,
    timestamp: notification.timestamp || new Date()
  }
  
  notifications.value.unshift(newNotification)
  
  // 限制通知数量，最多保留100条
  if (notifications.value.length > 100) {
    notifications.value = notifications.value.slice(0, 100)
  }
  
  saveNotificationsToStorage()
}

const saveNotificationsToStorage = () => {
  try {
    localStorage.setItem('notifications', JSON.stringify(notifications.value))
  } catch (error) {
    console.error('保存通知到本地存储失败:', error)
  }
}

const loadNotificationsFromStorage = () => {
  try {
    const stored = localStorage.getItem('notifications')
    if (stored) {
      notifications.value = JSON.parse(stored)
    }
  } catch (error) {
    console.error('从本地存储加载通知失败:', error)
    notifications.value = []
  }
}

// WebSocket消息处理器
const handleWebSocketMessage = (message) => {
  addNotification(message)
}

// 生命周期
onMounted(() => {
  loadNotificationsFromStorage()
  
  // 注册WebSocket消息处理器
  webSocketManager.addMessageHandler('NOTICE', handleWebSocketMessage)
  webSocketManager.addMessageHandler('SYSTEM', handleWebSocketMessage)
  webSocketManager.addMessageHandler('PRIVATE', handleWebSocketMessage)
})

onUnmounted(() => {
  // 移除WebSocket消息处理器
  webSocketManager.removeMessageHandler('NOTICE', handleWebSocketMessage)
  webSocketManager.removeMessageHandler('SYSTEM', handleWebSocketMessage)
  webSocketManager.removeMessageHandler('PRIVATE', handleWebSocketMessage)
})

// 暴露方法给父组件
defineExpose({
  addNotification
})
</script>

<style scoped>
.notification-center {
  position: relative;
}

.notification-badge {
  cursor: pointer;
}

.notification-button {
  padding: 8px;
  border: none;
  background: transparent;
  color: #606266;
  transition: color 0.3s;
}

.notification-button:hover {
  color: #409eff;
}

.notification-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.notification-actions {
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  gap: 8px;
}

.notification-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px 0;
}

.notification-item {
  padding: 12px;
  border-bottom: 1px solid #f5f7fa;
  cursor: pointer;
  transition: background-color 0.3s;
}

.notification-item:hover {
  background-color: #f5f7fa;
}

.notification-item.unread {
  background-color: #ecf5ff;
  border-left: 3px solid #409eff;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.notification-title {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}

.notification-content-text {
  color: #606266;
  font-size: 13px;
  line-height: 1.4;
  margin-bottom: 4px;
}

.notification-sender {
  font-size: 12px;
  color: #909399;
}

.empty-notifications {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}
</style>
